import os

def read_file_content(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except (UnicodeDecodeError, IOError):
        return None

def create_markdown_structure(root_dir, output_file):
    with open(output_file, 'w', encoding='utf-8') as f:
        for root, dirs, files in os.walk(root_dir):
            level = root.replace(root_dir, '').count(os.sep)
            indent = '    ' * level
            f.write(f"{indent}- **{os.path.basename(root)}/**\n")
            
            subindent = '    ' * (level + 1)
            for file in files:
                file_path = os.path.join(root, file)
                
                if file.endswith('.py'):
                    f.write(f"{subindent}- **{file}**\n\n")
                    f.write("    ```python\n")
                elif file.endswith('.md'):
                    f.write(f"{subindent}- **{file}**\n\n")
                    f.write("    ```markdown\n")
                elif file.endswith('.txt'):
                    f.write(f"{subindent}- **{file}**\n\n")
                    f.write("    ```text\n")
                elif file.endswith('.csv'):
                    f.write(f"{subindent}- **{file}**\n\n")
                    f.write("    ```text\n")
                elif file.endswith('.xlsx'):
                    f.write(f"{subindent}- **{file}** (Excel file, content skipped)\n")
                    continue
                else:
                    f.write(f"{subindent}- **{file}** (File type not recognized)\n")
                    continue

                content = read_file_content(file_path)
                if content:
                    f.write(f"{content}\n")
                f.write("    ```\n\n")




if __name__ == "__main__":
    root_directory = './my_query_project_new'  # 要记录的目录，例如当前目录 '.'
    output_markdown = 'project_structure_new.md'
    # 调用函数生成项目结构文档
    create_markdown_structure(root_directory, output_markdown)
    print(f"Project structure and file contents have been written to {output_markdown}")
